﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;

namespace WP7BackupService
{
	class TcpHelpers
	{
		public static int GetAvailablePort()
		{
			const int startingPort = 1024;
			IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
			//getting active connections 
			TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();

			List<int> portArray = new List<int>();
			portArray.AddRange(from n in connections
							   where n.LocalEndPoint.Port >= startingPort
							   select n.LocalEndPoint.Port);

			//getting active tcp listners - WCF service listening in tcp 
			IPEndPoint[] endPoints = properties.GetActiveTcpListeners();
			portArray.AddRange(from n in endPoints
							   where n.Port >= startingPort
							   select n.Port);

			//getting active udp listeners 
			endPoints = properties.GetActiveUdpListeners();
			portArray.AddRange(from n in endPoints
							   where n.Port >= startingPort
							   select n.Port);

			portArray.Sort();
			int i;
			for (i = startingPort; i < UInt16.MaxValue; i++)
				if (!portArray.Contains(i))
					return i;
			return i;
		}

		public static string GetIp()
		{
			IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
			IPAddress[] addr = ipEntry.AddressList;
			foreach (IPAddress t in addr.Where(t => t.AddressFamily == AddressFamily.InterNetwork))
				return t.ToString();
			return string.Empty;
		}
	}
}
